<?php defined('RUN_KATANA') or die('Restricted access');
class ProductGroup extends Object
{
	public $Title;
	public $TitleImport;
	public $Active;
	public $Providers;
	public $ProvidersLoaded;
	
	public function ProductGroup() 
	{ 
		self::setDataChanged(false);
		self::setProvidersLoaded(false);
	}
	
	public function __toString()
	{
		$out  = self::getTitle();
		return $out;
	}
	
	public function getTitle() { return $this->Title;  }
	public function getTitleImport() { return $this->TitleImport;  }
	public function getActive() { return intval($this->Active); }
	public function getLink() 
	{  
		$link  = '?g='.$this->Id;
		if(intval($_REQUEST['cID']) > 0)
		{ $link .= '&amp;cID='.intval($_REQUEST['cID']); }
		return $link; 
	}
	/* Providers */
	public function getProvider($id=0) 
	{
		if($id > 0)
		{
			self::loadProviders();
			if(isset($this->Providers[$id]))
			{ return $this->Providers[$id]; }
		}
	}
	public function getProviders() 
	{
		self::loadProviders();
		return $this->Providers; 
	}
	public function getProvidersLoaded() { return $this->ProvidersLoaded; }
	/* Groups */
	
	public function setTitle($val) { $this->Title=$val;  }
	public function setTitleImport($val) { $this->TitleImport=$val;  }
	public function setActive($val) { $this->Active=intval($val); }
	public function setProviders($val) { $this->Providers=$val; }
	public function setProvidersLoaded($val) { $this->ProvidersLoaded=$val; }
	public function loadProviders($id=0)
	{
		global $shop;
		global $db;
		$providers = $shop->getProviders();
		
		if((self::getId() > 0) && (self::getProvidersLoaded() == false))
		{
			$sql  = 'SELECT ptg.provider_id FROM '.DB_PERFIX.'product_provider_to_groups AS ptg ';
			$sql .= 'LEFT JOIN '.DB_PERFIX.'product_providers AS pr ON pr.id=ptg.provider_id ';
			$sql .= 'WHERE ptg.group_id='.self::getId().' AND pr.id=ptg.provider_id ';
			if($shop->getFrontend())
			{ $sql .= ' AND pr.active=1 '; }
			$sql .= 'ORDER BY pr.title ASC;';
			
			$data = $db->fetch($sql, CACHE_TTL);
			if(is_array($data))
			{
				foreach($data as $row)
				{ 
					if($shop->getProviders($row['provider_id']))
					{ $this->Providers[$row['provider_id']] = $shop->getProvider($row['provider_id']); }
				}
			}
			self::setProvidersLoaded(true);
		}
	}
	
	public function update()
	{
		if((self::getId() > 0) && (self::getDataChanged()))
		{
			$sql  = 'UPDATE '.DB_PERFIX.'product_groups SET ';
			$sql .= '`title`="'.self::formatText(self::getTitle()).'", ';
			$sql .= '`title_import`="'.self::formatText(self::getTitleImport()).'" ';
			$sql .= ' WHERE id='.self::getId().' LIMIT 1;';
			mysql_query($sql);
		}
	}
}
?>